package com.yangzihao.service.impl;

import com.yangzihao.entity.LoginUser;
import com.yangzihao.entity.User;
import com.yangzihao.service.LoginService;
import com.yangzihao.utils.JwtUtil;
import com.yangzihao.utils.RedisCache;
import com.yangzihao.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private  RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        //AuthenticationManager authenticate 进行用户认证

        //这个地方要传入一个Authentication类 所以我们得先创建一个Authentication，Authentication是一个接口我们找他的实现类

        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //如果认证没通过，给出对应的提示
        if(Objects.isNull(authenticate)){ //为null说明没有通过
            throw new RuntimeException("认证失败");
        }

        //如果认证通过  ，就使用userid生成一个 jwt存入 ResponseResult返回
        LoginUser loginUser=  (LoginUser)authenticate.getPrincipal();//这个其实就是UserDetailService返回的那个LoginUser
        //把完整的用户信息存入redis userId作为key
        String userId = loginUser.getUser().getId().toString();
        String jwt = JwtUtil.createJWT(userId);

        HashMap<String, String> map = new HashMap<>();
        map.put("token",jwt);

//      顺便将数据存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);

        return new ResponseResult<HashMap>(200,"登录成功",map);
    }

    @Override
    public ResponseResult logout() {
        Authentication authentication = (UsernamePasswordAuthenticationToken)SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        //拿到key
        redisCache.deleteObject("login:"+loginUser.getUser().getId());



        SecurityContextHolder.getContext().getAuthentication().getName();
        return new ResponseResult(200,"退出成功");
    }
}
